package com.bwie.service.impl;

import cn.hutool.core.util.IdUtil;
import com.bwie.common.constants.JwtConstants;
import com.bwie.common.constants.TokenConstants;
import com.bwie.common.domain.User;
import com.bwie.common.domain.UserRole;
import com.bwie.common.domain.response.UserResponse;
import com.bwie.common.result.Result;
import com.bwie.common.utils.JwtUtils;
import com.bwie.common.utils.StringUtils;
import com.bwie.exceptions.BizException;
import com.bwie.remote.RemoteSystemService;
import com.bwie.service.AuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @className: AuthServiceImpl
 * @Description: TODO
 * @version: v1.８.0
 * @author: 房新路
 * @date: 2025/8/4 10:33
 */
@Service
public class AuthServiceImpl implements AuthService {
    @Autowired
    private RemoteSystemService systemService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public UserResponse login(User user) {
        String username = user.getUsername();
        String password = user.getPassword();
        //非空
        if(!StringUtils.isNotBlank(username)){
            throw new BizException("用户名不能为空");
        }
        if(!StringUtils.isNotBlank(password)){
            throw new BizException("密码不能为空");
        }
        //正则
        if(!username.matches(".{8,}")){
            throw new BizException("用户名不能小于8位");
        }
        if(!password.matches("(?=.*[0-9])(?=.*[A-z]).{6,}")){
            throw new BizException("密码不能小于6位,密码必须包含字母和数字");
        }
        //判断该用户是否存在
        Result<User> byUsername = systemService.findByUsername(username);
        User byUsernameData = byUsername.getData();
        if(byUsernameData==null){
            throw new BizException("用户名不存在");
        }
        String dataPassword = byUsernameData.getPassword();
        //判断密码是否正确
        if(!Objects.equals(password,dataPassword)){
            throw new BizException("密码不正确");
        }
        Integer userId = byUsernameData.getId();
        Result<UserRole> byRole = systemService.findByRole(userId);
        UserRole roleData = byRole.getData();
        HashMap<String, Object> map = new HashMap<>();
        String userKey = IdUtil.fastSimpleUUID();
        map.put(JwtConstants.USER_KEY,userKey);
        String token = JwtUtils.createToken(map);
        redisTemplate.opsForValue().set(TokenConstants.LOGIN_TOKEN_KEY+userKey,roleData,30, TimeUnit.MINUTES);
        UserResponse userResponse = new UserResponse();
        userResponse.setToken(token);
        userResponse.setStrTime("30Min");
        return userResponse;
    }
}